﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Mmht.BT;
using System.Collections.Generic;
using System.IO;

public partial class admin_ymgl_yywz : System.Web.UI.Page
{
    private const string _pdfType = "展示页面";
    private PageBT _pbt;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["admin_id"] == null)
            {
                Response.Redirect("admin_logout.aspx");
                return;
            }
            if (!IsPostBack)
            {
                foreach (string pt in PageTypes.types)
                {
                    this.ddlSelectPage.Items.Add(pt);
                }
                ViewState["type"] = this.ddlSelectPage.Text;
                loadTable();
            }
        }
        catch
        {

        }
    }

    private void loadTable()
    {
        string _type = ViewState["type"].ToString();
        if (string.IsNullOrEmpty(_type))
        {
            this.GridView1.DataSource = null;
            this.GridView1.DataBind();
            return;
        }
        else
        {            
            _pbt = new PageBT();
            if (string.IsNullOrEmpty(_pbt.GetTitle(_type)))
            {
                message_show("在添加引用文章前 需要先对该类型的页面设置标题和正文");
                this.FindPdf.Enabled = false;
                this.UploadPicture.Enabled = false;
                this.GridView1.DataSource = null;
                this.GridView1.DataBind();
                return;
            }
            this.FindPdf.Enabled = true;
            this.UploadPicture.Enabled = true;
            DataTable table = new DataTable();
            table.Columns.Add("id");
            table.Columns.Add("name");
            string[] fids = _pbt.GetFiles(_type); 
            GetPdf gp = new GetPdf();
            foreach (string fid in fids)
            {
                DataRow row = table.NewRow();
                row["id"] = fid.Trim();
                DataRow pdfrow = gp.GetPdfById(int.Parse(fid));
                if (pdfrow == null)
                {
                    _pbt.DeleteFile(_type, fid.Trim());
                }
                else
                {
                    row["name"] = pdfrow["name_cn"].ToString();
                    table.Rows.Add(row);
                }
            }
            this.GridView1.DataSource = table;
            this.GridView1.DataBind();
        }
    }

    protected void ddlSelectPage_SelectedIndexChanged(object sender, EventArgs e)
    {
        ViewState["type"] = this.ddlSelectPage.Text;
        loadTable();
    }

    protected void UploadPicture_Click(object sender, EventArgs e)
    {
        try
        {
            string _type = ViewState["type"].ToString();
            if (string.IsNullOrEmpty(_type))
            {
                message_show("请选择页面类型");
                return;
            }
            string fe = System.IO.Path.GetExtension(this.FindPdf.FileName).ToLower();
            string fn = System.IO.Path.GetFileName(this.FindPdf.PostedFile.FileName).Trim();
            List<string> extList = new List<string>(new string[] { ".pdf" });
            if (extList.Contains(fe))
            {
                //保存pdf
                string fname = fn.Split('.')[0];
                string fpath = "files/pdf/page/";
                //检测文件夹内是否已经存在该文件名称
                DirectoryInfo mydir = new DirectoryInfo(Server.MapPath(fpath));
                int i = 0;
                foreach (FileSystemInfo fsi in mydir.GetFileSystemInfos())
                {
                    if (fsi is FileInfo)
                    {
                        FileInfo fi = (FileInfo)fsi;
                        string y = System.IO.Path.GetFileName(fi.FullName);
                        if (y == fn)
                        {
                            string msg = string.Format("上传失败：已经有页面引用“{0}”，为避免冲突，请更改该pdf的文件名后再上传。", fn);
                            message_show(msg);
                            return;
                        }
                    }
                }
                //保存文件到文件夹
                string furl = fpath + fn;
                this.FindPdf.PostedFile.SaveAs(Server.MapPath(furl));
                //将pdf记录添加到pdf表中
                DataTable dt = new DataTable();
                dt.Columns.Add("name_cn");
                dt.Columns.Add("url");
                DataRow row = dt.NewRow();
                row[0] = fname;
                row[1] = furl;
                dt.Rows.Add(row);
                int createdBy = int.Parse(Session["admin_id"].ToString());
                DateTime now = DateTime.Now;
                GetPdf gp = new GetPdf();
                gp.UploadPdf(dt, _pdfType, createdBy, now);
                //同时生成缩略图
                ImagePdf ip = new ImagePdf();
                ip.CreatePdfImageByName(fname, _pdfType);
                //获取id
                DataTable table = gp.GetPdfByName(fname, _pdfType);
                if (table.Rows == null || table.Rows.Count == 0)
                {
                    message_show("保存pdf出现错误");
                    return;
                }
                string id = table.Rows[0]["id"].ToString();
                //保存到page页面
                PageBT pbt = new PageBT();
                if (pbt.AddFile(_type, id))
                {
                    message_show("上传成功，且修改数据库");
                }
                else
                {
                    message_show("上传成功，但修改数据库失败。");
                }
                loadTable();
            }
            else
            {
                message_show("上传文件格式不正确，请选择pdf格式");
            }
        }
        catch
        {
            message_show("上传错误 ");
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string _type = ViewState["type"].ToString();
            string id = ((Button)sender).CommandArgument.ToString();
            PageBT pbt = new PageBT();
            if (pbt.DeleteFile(_type, id))
            {
                GetPdf gpdf = new GetPdf();
                DataRow row = gpdf.GetPdfById(int.Parse(id));
                //删除pdf表中的数据
                gpdf.DelPDF(_pdfType, int.Parse(id));
                //删除pdf文件
                string furl = row["pdf_url"].ToString();
                FileDelete fd = new FileDelete();
                fd.deleteFile(furl);
                //删除缩略图
                string iurl = row["image_url"].ToString();
                fd.deleteFile(iurl);
                message_show("删除成功");
            }
            loadTable();
        }
        catch
        {
            message_show("删除失败");
        }
    }

    /// <summary>
    /// 信息提示
    /// </summary>
    /// <param name="msg">提示信息</param>
    private void message_show(string msg)
    {
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "信息提示", "<script language='javascript'>  warning('" + msg + "');</script>");
    }
}
